package com.sfx.concurrent.demo.concurrent.LiveLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-07
 * Time: 17:30
 */

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * 活锁 : 两个线程互相改变对方的结束条件,最终谁也没有结束
 * 解决活锁: 执行时间有一定的交错-->让睡眠的时间是随机数
 * 能让其交错开,第一个线程马上要运行完了,第二个线程就没有机会改变对方的结束条件了
 */
@Slf4j(topic = "c.TestLiveLock")
public class TestLiveLock {
    private static int count = 10;

    public static void main(String[] args) {
        /**
         * t1线程想将count=10减到0
         */
        Random random = new Random();
        new Thread(() -> {
             while (count>0) {
                 try {
                     Thread.sleep(random.nextInt(100));
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 count--;
                 log.debug("count : {}",count);
             }
        },"t1").start();
        /**
         * t2线程想将count=10减到0
         */
        new Thread(() -> {
            while (count<20) {
                try {
                    Thread.sleep(random.nextInt(50));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                log.debug("count : {}",count);
            }
        },"t2").start();
    }
}
